package org.cypress.rtpack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.cypress.rtpack.entity.RtpackHostname;
import org.cypress.rtpack.entity.RtpackMoniip;
import org.cypress.rtpack.mapper.RtpackHostnameMapper;
import org.cypress.rtpack.service.IRtpackHostnameService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * @author getty
 */
@Service
public class RtpackHostnameServiceImpl extends ServiceImpl<RtpackHostnameMapper, RtpackHostname> implements IRtpackHostnameService {
    @Override
    public RtpackHostname getByIndex(Integer index) {
        LambdaQueryWrapper<RtpackHostname> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RtpackHostname::getIndex, index);     //RtpackMoni需要有getIndex方法，类需要@Data注解
        RtpackHostname rtpackHostname = this.getBaseMapper().selectOne(queryWrapper);
        return rtpackHostname;
    }

    @Override
    public RtpackHostname getByIP(String IP) {
        LambdaQueryWrapper<RtpackHostname> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RtpackHostname::getIP, IP);     //RtpackHost需要有getIP方法，类需要@Data注解
        RtpackHostname rtpackHostname = this.getBaseMapper().selectOne(queryWrapper);
        return rtpackHostname;
    }

    @Override
    @Transactional(readOnly = true)  // 自动管理连接生命周期
    public List<RtpackHostname> getAll() {
        LambdaQueryWrapper<RtpackHostname> queryWrapper = new LambdaQueryWrapper<>();
        List<RtpackHostname> rtpackHostnameList = this.getBaseMapper().selectList(queryWrapper);
        return rtpackHostnameList;
    }

    @Override
    public RtpackHostname updateByIndex(RtpackHostname inst) {
        // 1. 参数校验
        if (inst == null || inst.getIndex() == null) {
            throw new IllegalArgumentException("Config or key cannot be null");
        }

        // 2. 检查配置项是否存在
        LambdaQueryWrapper<RtpackHostname> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RtpackHostname::getIndex, inst.getIndex());
        RtpackHostname existing = getOne(queryWrapper);

        if (existing == null) {
            throw new RuntimeException("Config with key [" + inst.getIndex() + "] not found");
        }

        // 3. 保留原始ID（防止前端误传ID导致更新错误记录）
        inst.setIndex(existing.getIndex());

        // 4. 执行更新（MyBatis-Plus的updateById是原子操作）
        boolean success = updateById(inst);

        if (!success) {
            throw new RuntimeException("Update hostname failed");
        }

        // 5. 返回更新后的完整数据（避免返回前端可能修改过的对象）
        return getByIndex(inst.getIndex());
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务控制
    public List<RtpackHostname> batchUpdateByIndex(List<RtpackHostname> instList) {
        // 1. 参数校验
        if (CollectionUtils.isEmpty(instList)) {
            throw new IllegalArgumentException("Config list cannot be empty");
        }

        // 2. 检查所有key是否存在
        List<Integer> idxs = instList.stream()
                .map(RtpackHostname::getIndex)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        if (idxs.size() != instList.size()) {
            throw new IllegalArgumentException("Some hostnames have null keys");
        }

        // 3. 获取现有配置项映射表（一次性查询优化性能）
        Map<Integer, RtpackHostname> existingMap = listByIndexs(idxs).stream()
                .collect(Collectors.toMap(RtpackHostname::getIndex, Function.identity()));

        // 4. 准备待更新列表（保留原始ID）
        List<RtpackHostname> toUpdate = instList.stream()
                .peek(inst -> {
                    RtpackHostname existing = existingMap.get(inst.getIndex());
                    if (existing == null) {
                        throw new RuntimeException("Config with key [" + inst.getIndex() + "] not found");
                    }
                    inst.setIndex(existing.getIndex()); // 关键：绑定数据库ID
                })
                .collect(Collectors.toList());

        // 5. 批量更新（MyBatis-Plus的saveOrUpdateBatch）
        if (!updateBatchById(toUpdate)) {
            throw new RuntimeException("Batch update failed");
        }

        // 6. 返回更新后的最新数据
        return (List<RtpackHostname>) listByIds(toUpdate.stream().map(RtpackHostname::getIndex).collect(Collectors.toList()));
    }

    // 辅助方法：根据index批量查询
    private List<RtpackHostname> listByIndexs(List<Integer> idxs) {
        LambdaQueryWrapper<RtpackHostname> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RtpackHostname::getIndex, idxs);
        return list(queryWrapper);
    }

    /**
     * 物理删除所有记录（保留表结构）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteAllRecords() {
        return getBaseMapper().deleteAllRecords(); // 调用注解方法
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<RtpackHostname> batchInsert(List<RtpackHostname> list) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        saveBatch(list); // MyBatis-Plus的批量插入
        return list;
    }
}
